<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import DoctorCard from './DoctorCard.vue'
import { getDoctorList, appointDoctor, type DoctorRequest, type DoctorVO, type DoctorPageResponse } from '@/apis/doctor/doctorAPI'
import type { ApiResponse } from '@/types/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useDoctorDataStore } from '@/stores/doctorData'

// 搜索表单
const searchForm = reactive<DoctorRequest>({
  name: '',
  department: '',
  goodAt: '',
  title: '',
  pageNum: '1',
  pageSize: '12'
})

// 获取医生数据store
const doctorDataStore = useDoctorDataStore()

// 科室选项和职称选项
const departments = computed(() => doctorDataStore.departmentNames)
const titles = computed(() => doctorDataStore.titleNames)

// 医生列表数据
const doctorList = ref<DoctorVO[]>([])
const total = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)

// 获取医生列表数据
const fetchDoctorList = async () => {
  loading.value = true
  try {
    // 更新页码
    searchForm.pageNum = currentPage.value.toString()
    searchForm.pageSize = pageSize.value.toString()

    const res = await getDoctorList(searchForm)
    if (res.status === 200 && res.data) {
      doctorList.value = res.data.records
      total.value = res.data.total
    } else {
      console.error('获取医生列表失败:', res.message)
    }
  } catch (error) {
    console.error('获取医生列表异常:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置页码
  fetchDoctorList()
}

// 处理重置
const handleReset = () => {
  // 重置搜索表单
  searchForm.name = ''
  searchForm.department = ''
  searchForm.goodAt = ''
  searchForm.title = ''
  currentPage.value = 1
  fetchDoctorList()
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchDoctorList()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchDoctorList()
}

// 初始化路由
const router = useRouter()

// 获取用户信息
const authStore = useAuthStore()

// 查看医生详情
const viewDoctorDetail = (doctorId: number) => {
  router.push({
    path: '/user/online-consultation/doctorDetail',
    query: { id: doctorId.toString() }
  })
}

// 处理预约
const handleMakeAppointment = (doctorId: number) => {
  // 检查用户是否登录
  if (!authStore.isLoggedIn) {
    ElMessage.warning('请先登录后再进行预约')
    router.push('/login')
    return
  }

  // 显示确认对话框
  ElMessageBox.confirm('确定要预约该医生吗?', '预约确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const res = await appointDoctor(doctorId)
      if (res.code === 200 || res.status === 200) {
        ElMessage.success('预约成功')
        // 跳转到预约列表页面
        router.push('/user/user-appointment')
      } else {
        ElMessage.error(res.message || '预约失败')
      }
    } catch (error) {
      console.error('预约出错:', error)
      ElMessage.error('预约出错，请稍后重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 初始化加载数据
onMounted(async () => {
  // 先获取科室和职称数据
  if (!doctorDataStore.initialized.departments) {
    await doctorDataStore.fetchDepartments()
  }
  if (!doctorDataStore.initialized.titles) {
    await doctorDataStore.fetchTitles()
  }
  // 获取医生列表
  fetchDoctorList()
})
</script>

<template>
  <div class="doctor-list-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.name" placeholder="请输入医生姓名" clearable />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="searchForm.department" placeholder="请选择科室" clearable>
            <el-option v-for="dept in departments" :key="dept" :label="dept" :value="dept" />
          </el-select>
        </el-form-item>
        <el-form-item label="职称">
          <el-select v-model="searchForm.title" placeholder="请选择职称" clearable>
            <el-option v-for="title in titles" :key="title" :label="title" :value="title" />
          </el-select>
        </el-form-item>
        <el-form-item label="擅长领域">
          <el-input v-model="searchForm.goodAt" placeholder="请输入擅长领域" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 医生列表 -->
    <div class="doctor-grid">
      <el-row :gutter="20">
        <el-col v-for="doctor in doctorList" :key="doctor.id" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <DoctorCard
            :doctor="doctor"
            @view-detail="viewDoctorDetail"
            @make-appointment="handleMakeAppointment"
          />
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 无数据提示 -->
    <el-empty v-if="!loading && doctorList.length === 0" description="暂无医生数据" />

    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
  </div>
</template>

<style scoped>
.doctor-list-container {
  padding: 20px 0;
}

.search-card {
  margin-bottom: 20px;
}

.doctor-list-card {
  min-height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.doctor-col {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 调整科室和职称选择框的宽度 */
:deep(.el-select) {
  width: 180px;
}
</style>
